﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using hStatsC.Helper;
using hStatsC.Models;
using Panuon.UI.Silver;
using PropertyChanged;

namespace hStatsC.Views
{
    [AddINotifyPropertyChangedInterface]
    public partial class AppsView : UserControl
    {
        public ObservableCollection<AppInfo> Apps { get; set; }

        public AppsView()
        {
            InitializeComponent();
            DataContext = this;
            RefreshList();
        }

        private void Btn_TokenCopy(object sender, RoutedEventArgs e)
        {
            var t = ((sender as Button).DataContext as AppInfo).AccessToken;
            Clipboard.SetText(t);
            MessageBoxX.Show(t, "复制成功!");
        }

        private void Btn_Edit(object sender, RoutedEventArgs e)
        {
            var w = new AppDetailsView(false);
            w.DataContext = ((Button) sender).DataContext as AppInfo;
            w.ShowDialog();
        }

        private void Btn_AddApp(object sender, RoutedEventArgs e)
        {
            try
            {
                var w = new AppDetailsView(true);
                if (w.ShowDialog() == true)
                {
                    if (MainHelper.AddApp(w.App.App))
                    {
                        MessageBoxX.Show("添加App成功!\n正在为你刷新数据...", "成功");
                        RefreshList();
                    }
                    else
                    {
                        MessageBoxX.Show("添加App失败!\n似乎是已有重复的Appid了...", "失败");
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }

        private void RefreshList()
        {
            MainHelper.GetAppInfos();
            this.Apps = App.Apps;
        }

        private void Btn_Remove(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MainHelper.RemoveApp(((sender as Button)?.DataContext as AppInfo)?.App))
                {
                RefreshList();
                MessageBoxX.Show("删除成功!", "成功");
                    
                }
                else
                {
                    MessageBoxX.Show("删除失败!(应用已经不存在)", "失败");
                }
            }
            catch (Exception exception)
            {
                MessageBoxX.Show("删除用户的App错误(也许你这个App存在数个版本或启动记录。)\n请联系管理员删除其他记录", "异常");
            }
        }
    }
}